package com.example.homelicaisystem.config;

import com.example.homelicaisystem.services.UserService;
import com.example.homelicaisystem.utils.UserUtil;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAdvice {
	private final UserService userService;

	public LogAdvice(UserService userService) {
		this.userService = userService;
	}

	//指定某一个包和子包。。
	@Before("within(com.example.homelicaisystem.control..*)")
	public void logControl(JoinPoint point) {
		log.info("qq:{}", Arrays.toString(point.getArgs()));
		log.info("类:{}，args:{}", point.getTarget(), point.getArgs());
	}

	@Around("@annotation(com.example.homelicaisystem.config.Permission)")
	public Object handlePermission(ProceedingJoinPoint point) throws Throwable {
		//得到方法签名
		Signature sig = point.getSignature();
		MethodSignature ms = (MethodSignature) sig;
		//得到方法
		Method m = point.getTarget().getClass().getDeclaredMethod(ms.getName(), ms.getParameterTypes());
		//通过方法得到注解
		Permission permission = m.getAnnotation(Permission.class);

		//把注解值和用户id传入，求是否具有权限
		if (userService.hasPower(UserUtil.getUserId(), permission.value())) {
			//执行原方法
			return point.proceed(point.getArgs());
		} else {
			throw new RuntimeException("没有操作权限");
		}
	}

	//	@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
//	private void aaaa() {
//	}
//
//	//在指定的bean的所有方法
//	@Pointcut("bean(userControl)")
//	private void bb() {
//	}

//	//指定执行方法。
//	@Pointcut("execution(* com.example.springtrea..services.*.*(..))")
//	public void businessService() {
//	}

//	@Before("bean(userControl)")
//	public void testBeforePointcut(JoinPoint point) {
//		log.info("来吧:{}", Arrays.toString(point.getArgs()));
//	}

//	@Before(value = "execution(* com.example.springtrea..control.UserControl.del(..))",argNames="id")
//	public void hhhh(int id) {
//		log.info("获得一个参数:{}", id);
//	}
//
//	@Before("bb()")
//	public void bbbefore(JoinPoint point) {
//		log.info(":{}", Arrays.toString(point.getArgs()));
//	}
//
//	@Around("aaaa()")
//	public Object log(ProceedingJoinPoint point) throws Throwable {
//		log.error("切面得到一个get应用。{}", point);
//		return point.proceed();
//	}
//
//	@Before("aaaa()")
//	public void l(JoinPoint point) {
//		log.info("Get方法获得参数:{}", Arrays.toString(point.getArgs()));
//	}
}
